<template>
  <div class="main-container container-limited container-fluid page-holder">
    <div class="page-title-holder">
      <h2 class="page-title">加入群组</h2>
    </div>
    <template v-if="Object.keys(group).length">
      <h3>{{ group.title }}</h3>
      <p>{{ group.desc }}</p>
      <template v-if="form.conditions.length">
        <el-alert type="warning" title="群组设置了加入条件，请填写如下信息" />
        <el-form ref="form" label-position="top" class="bold-label" :model="form">
          <el-form-item
            v-for="(condition, index) in form.conditions"
            :key="condition.key"
            :label="condition.key"
            :prop="`conditions.${index}.value`"
            :rules="{ required: true, message: `${condition.key}不能为空` }"
          >
            <el-input v-model="condition.value" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit" :loading="loading">确定加入</el-button>
          </el-form-item>
        </el-form>
      </template>
    </template>
    <template v-else>
      <h3>正在搜索群组...</h3>
    </template>
  </div>
</template>

<script>
import { formatGroup } from '../format';

export default {
  name: 'GroupsJoin', // 加入群组
  data() {
    return {
      group: {},
      form: {
        conditions: [],
      },
      loading: false,
    };
  },
  computed: {
    joinKey() { return this.$route.params.joinKey; },
  },
  created() {
    this.loadJoinConditions();
  },
  methods: {
    // 加载群组条件
    loadJoinConditions() {
      this.$api.groups.getJoinConditions({ joinKey: this.joinKey })
        .then((res) => {
          const groupData = formatGroup(res.data);
          if (groupData.joinConditions.length) {
            this.group = groupData;
            this.form.conditions = groupData.joinConditions.map(condition => ({ key: condition, value: '' }));
          } else this.join();
        })
        .catch((err) => { if (err) this.goBack(); });
    },
    // 提交信息
    onSubmit() {
      this.$refs.form.validate((valid, errs) => {
        if (valid) this.join();
        else this.$refs[Object.keys(errs)[0]][0].$el.scrollIntoView({ block: 'center' });
      });
    },
    // 加入群组
    join() {
      this.loading = true;
      this.$api.groups.join({
        joinKey: this.joinKey,
        conditions: Object.assign({}, ...this.form.conditions.map(c => ({ [c.key]: c.value }))),
      }).then((res) => {
        this.$message.success('加入成功');
        this.$router.push(`/groups/${res.data.id}`);
      }).catch(() => {})
        .then(() => { this.loading = false; });
    },
  },
  watch: {
    joinKey() {
      this.group = {};
      this.loadJoinConditions();
    },
  },
};
</script>

<style></style>
